package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.rmi.RemoteException;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /**
     * 用户保存
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 上传头像
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //上传图片到阿里云
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //调用百度aip检测图片是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        if (!detect){
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //如果包含人脸就更新数据
            UserInfo userInfo = new UserInfo();
            //将新的id设置到新的userInfo对象
            userInfo.setId(Long.valueOf(id));
            //设置将当前头像设置到userInfo对象中
            userInfo.setAvatar(imageUrl);
            //上传头像
            userInfoApi.update(userInfo);
        }
    }

    //根据id查询用户
    public UserInfoVo finfById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);
        Integer age = userInfo.getAge();
        if (age!=null){
            vo.setAge(age.toString());
        }
        return vo;
    }

    /**
     * 修改用户信息
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
